<template>
  <el-dialog
      :fullscreen="true"
      top="10vh"
      fullscreen
      width="800px"
      title="添加/编辑产品"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <SubmitForm
        :rule-form="ruleForm"
        :rules="rules"
        :form-list="formList"
        @change="handleFormChange"
        @save="onSave"
        @close="dialogValue = false"
    >
      <template v-slot:description>
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="行程亮点" name="highlights">
            <RichEditor v-model="ruleForm.highlights" />
          </el-tab-pane>
          <el-tab-pane label="产品详情" name="description">
            <RichEditor v-model="ruleForm.description" />
          </el-tab-pane>
          <el-tab-pane label="费用包含" name="cost_included">
            <RichEditor v-model="ruleForm.cost_included" />
          </el-tab-pane>
          <el-tab-pane label="费用不含" name="cost_excluded">
            <RichEditor v-model="ruleForm.cost_excluded" />
          </el-tab-pane>
          <el-tab-pane label="退款规则" name="refund_rules">
            <RichEditor v-model="ruleForm.refund_rules" />
          </el-tab-pane>
          <el-tab-pane label="预定须知" name="booking_notice">
            <RichEditor v-model="ruleForm.booking_notice" />
          </el-tab-pane>
          <el-tab-pane label="酒店级别" name="hotel_levels">
            <div class="hotel-levels-container">
              <div class="hotel-levels-header">
                <h4>酒店级别配置</h4>
                <el-button type="primary" size="small" @click="addHotelLevel">
                  <i class="el-icon-plus"></i> 添加级别
                </el-button>
              </div>
              <div class="hotel-levels-list">
                <el-table :data="ruleForm.hotel_levels" border style="width: 100%">
                  <el-table-column prop="level_name" label="级别名称" width="200">
                    <template slot-scope="scope">
                      <el-input 
                        v-model="scope.row.level_name" 
                        placeholder="请输入级别名称"
                        size="small">
                      </el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="价格" width="200">
                    <template slot-scope="scope">
                      <el-input-number 
                        v-model="scope.row.price" 
                        :precision="2" 
                        :step="0.01" 
                        :min="0"
                        size="small"
                        placeholder="请输入价格">
                      </el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="描述" min-width="200">
                    <template slot-scope="scope">
                      <el-input 
                        v-model="scope.row.description" 
                        placeholder="请输入级别描述"
                        size="small">
                      </el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="single_diff" label="单房差" width="150">
                    <template slot-scope="scope">
                      <el-input-number 
                        v-model="scope.row.single_diff" 
                        :precision="2" 
                        :step="0.01" 
                        :min="0"
                        size="small"
                        placeholder="单人间差价">
                      </el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="排序" width="120">
                    <template slot-scope="scope">
                      <el-input-number 
                        v-model="scope.row.sort" 
                        :min="0"
                        :step="1"
                        size="small"
                        placeholder="排序值"
                        @change="onSortChange">
                      </el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                      <el-button 
                        type="danger" 
                        size="mini" 
                        @click="removeHotelLevel(scope.$index)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="ruleForm.hotel_levels.length === 0" class="empty-tip">
                  <p>暂无酒店级别配置，请点击"添加级别"按钮进行配置</p>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
    </SubmitForm>

  </el-dialog>
</template>

<script>
import {http} from '@/api'

export default {
  name: 'ProductAdd',
  data() {
    return {
      apiKey: 'travel',
      dialogValue: false,
      activeTab: 'highlights', // 当前激活的标签页
      ruleForm: {},
      defaultForm: {
        name: '',
        cover: '',
        images: '',
        description: '',
        category_id: '',
        sort: 0,
        status: 1,
        price_text: '',
        share_price: '',
        is_virtual: 0,
        transportation_flag: 0,
        departure_city: '',
        destination_city: '',
        highlights: '', // 行程亮点
        details: '', // 产品详情
        cost_included: '', // 费用包含
        cost_excluded: '', // 费用不含
        refund_rules: '', // 退款规则
        booking_notice: '', // 预定须知
        hotel_levels: [] // 酒店级别列表，包含level_name、price、description、single_diff、sort字段
      },
      rules: {
        name: [{required: true, message: '产品名称不能为空'}],
        cover: [{required: true, message: '产品封面不能为空'}],
        category_id: [{required: true, message: '产品分类不能为空'}],
      },
      formList: [
        {
          label: '产品分类',
          prop: 'category_id',
          name: 'select',
          colSpan: 12,
          placeholder: '请选择产品分类',
          options: []
        },
        {
          label: '产品名称',
          prop: 'name',
          name: 'input',
          type: 'textarea',
          colSpan: 12,
          placeholder: '请输入产品名称'
        },
        {
          label: '产品封面',
          prop: 'cover',
          name: 'file',
          colSpan: 12
        },
        {
          label: '产品轮播图',
          prop: 'images',
          name: 'file',
          colSpan: 12,
          multiple: true
        },

        // {
        //   label: '是否包含大交通',
        //   prop: 'transportation_flag',
        //   name: 'switch',
        //   colSpan: 8,
        //   activeValue: 1,
        //   inactiveValue: 0,
        //   activeText: '是',
        //   inactiveText: '否'
        // },
        {
          label: '今日推荐',
          prop: 'is_virtual',
          name: 'radio',
          colSpan: 8,
          options: [
            { value: 1, label: '是' },
            { value: 0, label: '否' },
          ]
        },
        {
          label: '状态',
          prop: 'status',
          name: 'switch',
          colSpan: 8,
          activeValue: 1,
          inactiveValue: 0,
          activeText: '上架',
          inactiveText: '下架'
        },
        {
          label: '排序',
          prop: 'sort',
          name: 'number',
          colSpan: 8,
          min: 0
        },
        // 最低价price_text
        {
          label: '最低价',
          prop: 'price_text',
          name: 'input',
          colSpan: 8,
          placeholder: '请输入最低价'
        },
        {
          label: '最低价佣金',
          prop: 'share_price',
          name: 'input',
          colSpan: 8,
          placeholder: '请输入最低价佣金'
        },
        {
          label: '出发地',
          prop: 'departure_city',
          name: 'input',
          colSpan: 8,
          placeholder: '请输入出发地'
        },
        {
          label: '目的地',
          prop: 'destination_city',
          name: 'input',
          colSpan: 8,
          placeholder: '请输入目的地'
        },
        {
          label: '详情',
          prop: 'description',
          name: 'rich',
          colSpan: 24,
          slot: true
        },
        // {
        //   label: '分销价',
        //   prop: 'share_price',
        //   name: 'number',
        //   colSpan: 8,
        //   min: 0,
        //   precision: 2,
        //   step: 0.01
        // },
       
      ]
    }
  },
  mounted() {
    this.loadCategories();
  },
  methods: {
    loadCategories() {
      // 加载产品分类
      http.travelCategory.list().then(res => {
        this.formList[0].options = res.data.map(item => ({
          value: item.id,
          label: item.name
        }));
      });
    },
    handleFormChange({key, val}) {
      // 处理表单变化
    },
    // 添加酒店级别
    addHotelLevel() {
      if (!this.ruleForm.hotel_levels) {
        this.ruleForm.hotel_levels = [];
      }
      this.ruleForm.hotel_levels.push({
        level_name: '',
        price: 0,
        description: '',
        single_diff: 0,
        sort: this.ruleForm.hotel_levels.length
      });
    },
    // 删除酒店级别
    removeHotelLevel(index) {
      this.ruleForm.hotel_levels.splice(index, 1);
      // 重新排序剩余的酒店级别
      this.ruleForm.hotel_levels.forEach((level, idx) => {
        level.sort = idx;
      });
    },
    // 排序变化处理
    onSortChange() {
      // 根据sort字段重新排序酒店级别
      this.ruleForm.hotel_levels.sort((a, b) => a.sort - b.sort);
    },
    open(row) {
      this.dialogValue = true
      if (row) {
        http[this.apiKey].read(row.id).then(res => {
          let hotel_levels = []
          if (res.data.hotel_levels) {
            hotel_levels = JSON.parse(res.data.hotel_levels)
            // 确保每个酒店级别都有必要的字段
            hotel_levels.forEach((level, index) => {
              if (typeof level.sort === 'undefined') {
                level.sort = index;
              }
              if (typeof level.single_diff === 'undefined') {
                level.single_diff = 0;
              }
            });
            // 根据sort字段排序
            hotel_levels.sort((a, b) => a.sort - b.sort);
          }
          this.ruleForm = {
            ...res.data,
            hotel_levels: hotel_levels
          }
        })
      } else {
        this.ruleForm = {
          ...this.defaultForm,
          hotel_levels: [
          ]
        }
      }
    },
    onSave() {
      // 验证酒店级别数据
      if (this.ruleForm.hotel_levels && this.ruleForm.hotel_levels.length > 0) {
        for (let i = 0; i < this.ruleForm.hotel_levels.length; i++) {
          const level = this.ruleForm.hotel_levels[i];
          if (!level.level_name || level.level_name.trim() === '') {
            this.$message.error(`第${i + 1}行酒店级别名称不能为空`);
            return;
          }
          if (level.price <= 0) {
            this.$message.error(`第${i + 1}行酒店级别价格必须大于0`);
            return;
          }
        }
      }
      
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, {
        ...this.ruleForm,
        hotel_levels: JSON.stringify(this.ruleForm.hotel_levels)
      }).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      })
    }
  }
}
</script>

<style scoped lang="scss">
.el-tabs {
  margin-top: 20px;
  
  .el-tab-pane {
    padding: 20px;
    min-height: 400px;
  }
}

.rich-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  
  .ql-editor {
    min-height: 350px;
  }
}

.hotel-levels-container {
  .hotel-levels-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h4 {
      margin: 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }
  }
  
  .hotel-levels-list {
    .el-table {
      .el-table__header {
        background-color: #f5f7fa;
        
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }
      
      .el-table__row {
        &:hover {
          background-color: #f5f7fa;
        }
      }
      
      .el-input,
      .el-input-number {
        .el-input__inner {
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          
          &:focus {
            border-color: #409eff;
          }
        }
      }
      
      .el-button--danger {
        padding: 5px 10px;
        font-size: 12px;
        
        &:hover {
          background-color: #f56c6c;
          border-color: #f56c6c;
        }
      }
      
      .el-button--text {
        padding: 5px;
        font-size: 14px;
        color: #409eff;
        
        &:hover:not(:disabled) {
          color: #66b1ff;
          background-color: #ecf5ff;
        }
        
        &:disabled {
          color: #c0c4cc;
          cursor: not-allowed;
        }
        
        i {
          font-size: 16px;
        }
      }
    }
    
    .empty-tip {
      text-align: center;
      color: #909399;
      padding: 40px 0;
      
      p {
        margin: 0;
        font-size: 14px;
      }
    }
  }
}
</style>
